import {ref} from 'vue'
import {defineStore} from 'pinia'
import {loginAPI} from "@/apis/user.js";
import {useCartStore} from "@/stores/cartStore.js";
import {mergeCartAPI} from "@/apis/cart.js";

export const userStore = defineStore('user', () => {
    const user = ref({})
    let cartStore = useCartStore();
    const getUserInfo = async (account, password) => {
        const res = await loginAPI(account, password)
        user.value = res.result;
        // 合并购物车的操作
        await mergeCartAPI(cartStore.cartList.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))
        cartStore.updateNewList()
    }
    const clearUserInfo = async () => {
        //清除数据
        user.value = {}
        cartStore.clearCart();
    };
    return {user, getUserInfo,clearUserInfo}
},{
    //持久化插件
    //f12>application>local storage,点开里面会有个key,叫user,value就是上面的  const user
    //在获取数据(state,也就是user时)时会优先从local storage里面取,这样在关闭页面时也不会退出，如果不用这个插件就是pinia存到内存里面，关闭页面就退出登录了
    persist: true,
})
